// Created by wangliang on 2025/2/12.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:flutter_app_demo/utils/toast.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:mvvm_plus/mvvm_plus.dart';

class CommonWebPageViewModel extends ViewModel {
  final String url;

  late InAppWebViewController _controller;

  get controller => _controller;

  CommonWebPageViewModel({required this.url});

  @override
  void initState() {
    super.initState();
  }

  void initController(InAppWebViewController controller) {
    _controller = controller;

    // window.flutter_inappwebview.callHandler('test', {a:1, b:'aaa'}).then(response =>{})
    _registerJsCallHandler();
  }

  _registerJsCallHandler() {
    _controller.addJavaScriptHandler(
        handlerName: 'test',
        callback: (arguments) async {
          Log.d("arguments ${arguments[0]['name']}");
          await Future.delayed(const Duration(seconds: 3));
          return "This is the data return from dart";
        });
    _controller.addJavaScriptHandler(
        handlerName: 'showToast',
        callback: (args) {
          if (args.isNotEmpty) {
            var paramsStr = args[0]['params'] as String? ?? "";
            ToastUtil.showToast(context, paramsStr);
          }
        });

    _controller.addJavaScriptHandler(
        handlerName: 'testAsyncReturnFlutterCallJsReturn',
        callback: (args) {
          if (args.isNotEmpty) {
            var paramsStr = jsonEncode(args[0]);
            ToastUtil.showToast(context, paramsStr);
          }
        });
  }

  void callJs() async {
    // dart 调用 js
    var data = await _controller.evaluateJavascript(
        source: "testAsyncReturnFlutterCallJs('I am flutter')");
    Log.d('WLTest $data');
    ToastUtil.showToast(context, data.toString());
  }

  void callAsyncJs() {
    _controller.evaluateJavascript(
        source: "testAsyncReturnFlutterCallJs('I am flutter')");
  }
}
